//
//  WPMineMyCollectionRecordCVC.m
//  wobingwoyi
//
//  Created by WGP on 16/9/21.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPMineMyCollectionRecordCVC.h"
#import "WPMineCaseesCell.h"
#import "WPMineLoginVC.h"
#import "WPNewReadingIndivalCaseCell.h"

@interface WPMineMyCollectionRecordCVC ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UILabel *noRecordLabel;
@property(nonatomic,strong)UIImageView *noRecordView;
@property(nonatomic,assign)NSInteger row;
@property(nonatomic,strong)UIAlertView *alertView;

@end
@implementation WPMineMyCollectionRecordCVC

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self noRecordView];
        [self noRecordLabel];
        [self tableView];
    }
    return self;
}

-(UIImageView *)noRecordView
{
    if (_noRecordView == nil)
    {
        _noRecordView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"collection_record"]];
        [_noRecordView sizeToFit];
        [self.contentView addSubview:_noRecordView];
        
        [_noRecordView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.contentView);
            make.top.equalTo(self.contentView).offset(80*K_SCALE_ELSE_TABBAR);
        }];
    }
    return _noRecordView;
}

-(UILabel *)noRecordLabel
{
    if (_noRecordLabel == nil)
    {
        _noRecordLabel = [UILabel new];
        _noRecordLabel.text = @"暂无收藏记录";
        _noRecordLabel.font = [UIFont systemFontOfSize:14];
        _noRecordLabel.textColor = GloballightFontColor;
        [_noRecordView sizeToFit];
        [self.contentView addSubview:_noRecordLabel];
        
        [_noRecordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.contentView);
            make.top.equalTo(self.noRecordView.mas_bottom).offset(35*K_SCALE_ELSE_TABBAR);
        }];
    }
    return _noRecordLabel;
}

-(UITableView *)tableView
{
    if (_tableView == nil)
    {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor orangeColor];
        
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 200;
        
        _tableView.backgroundColor = GlobalBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
        headerView.backgroundColor = GlobalBgColor;
        _tableView.tableHeaderView = headerView;
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[WPMineCaseesCell class] forCellReuseIdentifier:@"famousDoctor"];
        [_tableView registerClass:[WPNewReadingIndivalCaseCell class] forCellReuseIdentifier:@"WPNewReadingIndivalCaseCell"];
        [self.contentView addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.contentView);
            make.top.equalTo(self.contentView);
        }];
        
        
        /* 配置下拉刷新控件 */
        MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //      刷新数据
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.tableView.mj_header endRefreshing];
                
            });
            
        }];
        self.tableView.mj_header = mj_header;
        [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
        [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
        [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
        mj_header.stateLabel.textColor = GLobalFontColor;
        mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
        
        //    上拉刷新控件
        MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
//            [self loadMoreData];
            [mj_footer endRefreshing];
        }];
//        self.tableView.mj_footer = mj_footer;
        mj_footer.automaticallyRefresh = NO;
        mj_footer.automaticallyHidden = YES;
        
    }
    return _tableView;
}

#pragma mark - 数据源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.collectRecordsArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewReadingIndivalCaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPNewReadingIndivalCaseCell"];
    
        UILongPressGestureRecognizer* longgs=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longpress:)];
        [cell addGestureRecognizer:longgs];//为cell添加手势
        longgs.minimumPressDuration=1.0;//定义长按识别时长
        longgs.view.tag=indexPath.row;//将手势和cell的序号绑定
    
    cell.model = self.collectRecordsArr[indexPath.item];
    
    cell.tapTriggered = ^{
        
        if (self.cellDidClickBlock)
        {
            self.cellDidClickBlock(self.collectRecordsArr[indexPath.item]);
        }
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPMRModel *model = self.collectRecordsArr[indexPath.item];
    
    if (self.cellDidClickBlock)
    {
        self.cellDidClickBlock(model);
    }
}

//长按手势
-(void)longpress:(UILongPressGestureRecognizer*)ges
{
    if (ges.state == UIGestureRecognizerStateBegan)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您确定要删除该条收藏记录吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        
        //        //获取目标cell
        self.row=ges.view.tag;
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        WPMRModel *model = self.collectRecordsArr[self.row];
        
        NSString *url = @"record/deleteCollect.do";
        NSDictionary *dict = @{@"recordId":@(model.id)};
        
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if ([responseObject[@"result"] isEqualToString:@"success"])
            {
                    //删除操作
                [self.collectRecordsArr removeObjectAtIndex:self.row];
                
                if(self.collectRecordsArr.count > 1)
                {
                        NSIndexPath *index =[NSIndexPath indexPathForRow:self.row inSection:0];
                        NSArray* deletearr=@[index];
                        [self.tableView deleteRowsAtIndexPaths:deletearr withRowAnimation:UITableViewRowAnimationFade];
                }
                else
                {
                            [self.tableView reloadData];
                }
            }
            else
            {
                if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                {
                    //                账号过期
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    self.alertView = alertView;
                    [alertView show];
                }
                else
                {
                    [self showErrorInfoWithStatus:@"网络错误"];
                }

            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self showErrorInfoWithStatus:@"网络错误"];
        }];

   }
    else if (buttonIndex == 0)
    {
        if (alertView == self.alertView)
        {
            //        WPMineLoginVC *vc = [WPMineLoginVC new];
            //        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
            //        vc.successLoginBlock = ^
            //        {
            //
            //        };
//            NSLog(@"账号过期");
        }
    }

}

-(void)setCollectRecordsArr:(NSMutableArray *)collectRecordsArr
{
    _collectRecordsArr = collectRecordsArr;
    if (!collectRecordsArr.count)
    {
        self.tableView.hidden = YES;
    }
    else
    {
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    }
    
}

-(void)setNoRecordStr:(NSString *)noRecordStr
{
    _noRecordStr = noRecordStr;
    self.noRecordLabel.text = noRecordStr;
}
@end
